<template>
  <div class="page-container">
    <div class="page-header">
      <div class="header-content">
        <h2>材料库存管理</h2>
        <div class="header-actions">
          <el-button type="primary" @click="openImportDialog">
            <el-icon><Upload /></el-icon>
            批量导入
          </el-button>
          <el-button type="success" @click="openAddDialog">
            <el-icon><Plus /></el-icon>
            新增材料
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="材料名称">
          <el-input
            v-model="filterForm.name"
            placeholder="请输入材料名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="材料编码">
          <el-input
            v-model="filterForm.code"
            placeholder="请输入材料编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="filterForm.category"
            placeholder="请选择分类"
            clearable
            style="width: 150px"
          >
            <el-option label="电子元件" value="electronic" />
            <el-option label="机械配件" value="mechanical" />
            <el-option label="办公用品" value="office" />
            <el-option label="清洁用品" value="cleaning" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="充足" value="sufficient" />
            <el-option label="不足" value="insufficient" />
            <el-option label="缺货" value="out_of_stock" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadMaterials">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 材料列表 -->
    <el-card class="table-card">
      <el-table
        :data="materials"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="code" label="材料编码" width="120" />
        <el-table-column prop="name" label="材料名称" min-width="150" />
        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)">
              {{ getCategoryLabel(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格型号" min-width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="stock_quantity" label="当前库存" width="100">
          <template #default="{ row }">
            <span :class="getStockClass(row)">
              {{ row.stock_quantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="min_stock" label="最低库存" width="100" />
        <el-table-column prop="max_stock" label="最高库存" width="100" />
        <el-table-column prop="unit_price" label="单价" width="100">
          <template #default="{ row }">
            ¥{{ row.unit_price?.toFixed(2) || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="supplier" label="供应商" min-width="120" />
        <el-table-column prop="location" label="存放位置" min-width="120" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row)">
              {{ getStatusLabel(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editMaterial(row)">
              编辑
            </el-button>
            <el-button type="warning" size="small" @click="adjustStock(row)">
              调整库存
            </el-button>
            <el-button type="danger" size="small" @click="deleteMaterial(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadMaterials"
          @current-change="loadMaterials"
        />
      </div>
    </el-card>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="批量导入材料"
      width="800px"
      @close="closeImportDialog"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="字段配置" name="config">
          <div class="import-config">
            <h4>选择导入字段</h4>
            <el-checkbox-group v-model="selectedFields">
              <div class="field-grid">
                <el-checkbox
                  v-for="field in importFields"
                  :key="field.key"
                  :label="field.key"
                  :disabled="field.required"
                >
                  <span>{{ field.label }}</span>
                  <el-tag v-if="field.required" type="danger" size="small">必填</el-tag>
                  <el-tag :type="getFieldTypeColor(field.type)" size="small">
                    {{ getFieldTypeLabel(field.type) }}
                  </el-tag>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </el-tab-pane>

        <el-tab-pane label="模板下载" name="template">
          <div class="template-section">
            <h4>导入说明</h4>
            <el-alert
              title="导入注意事项"
              type="info"
              :closable="false"
              show-icon
            >
              <ul>
                <li>请使用CSV格式文件，编码为UTF-8</li>
                <li>材料编码不能重复，如果编码已存在将更新该材料信息</li>
                <li>数值字段请填写数字，不要包含单位或其他字符</li>
                <li>分类字段请使用：electronic、mechanical、office、cleaning、other</li>
                <li>文件大小不超过10MB</li>
              </ul>
            </el-alert>

            <div class="template-actions">
              <el-button type="primary" @click="downloadTemplate">
                <el-icon><Download /></el-icon>
                下载导入模板
              </el-button>
              <el-button type="primary" @click="downloadSampleData">
                <el-icon><Document /></el-icon>
                下载示例数据
              </el-button>
            </div>

            <div class="template-preview">
              <h4>模板预览</h4>
              <el-table :data="templatePreview" border size="small">
                <el-table-column
                  v-for="column in templateColumns"
                  :key="column.key"
                  :prop="column.key"
                  :label="column.label"
                  :width="column.width"
                />
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="文件上传" name="upload">
          <div class="upload-section">
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :show-file-list="true"
              :limit="1"
              accept=".csv"
              :before-upload="beforeUpload"
              :on-change="handleFileChange"
              drag
            >
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                将CSV文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传CSV文件，且不超过10MB
                </div>
              </template>
            </el-upload>

            <div v-if="uploadFile" class="file-info">
              <h4>文件信息</h4>
              <p>文件名：{{ uploadFile.name }}</p>
              <p>文件大小：{{ formatFileSize(uploadFile.size) }}</p>
              <p>上传时间：{{ new Date().toLocaleString() }}</p>
            </div>

            <div v-if="previewData.length > 0" class="preview-section">
              <h4>数据预览（前5行）</h4>
              <el-table :data="previewData.slice(0, 5)" border size="small" max-height="300">
                <el-table-column
                  v-for="column in previewColumns"
                  :key="column.key"
                  :prop="column.key"
                  :label="column.label"
                  min-width="100"
                  show-overflow-tooltip
                />
              </el-table>
              <p class="preview-info">共 {{ previewData.length }} 条数据</p>
            </div>

            <div v-if="validationErrors.length > 0" class="error-section">
              <h4>数据验证错误</h4>
              <el-alert
                v-for="(error, index) in validationErrors.slice(0, 10)"
                :key="index"
                :title="error"
                type="error"
                :closable="false"
                style="margin-bottom: 8px"
              />
              <p v-if="validationErrors.length > 10" class="error-more">
                还有 {{ validationErrors.length - 10 }} 个错误...
              </p>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeImportDialog">取消</el-button>
          <el-button
            v-if="activeTab === 'upload' && previewData.length > 0"
            type="primary"
            @click="handleImport"
            :loading="importLoading"
            :disabled="validationErrors.length > 0"
          >
            确认导入
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增/编辑材料对话框 -->
    <el-dialog
      v-model="showMaterialDialog"
      :title="isEdit ? '编辑材料' : '新增材料'"
      width="600px"
    >
      <el-form
        ref="materialFormRef"
        :model="materialForm"
        :rules="materialRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="材料编码" prop="code">
              <el-input v-model="materialForm.code" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材料名称" prop="name">
              <el-input v-model="materialForm.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="materialForm.category" style="width: 100%">
                <el-option label="电子元件" value="electronic" />
                <el-option label="机械配件" value="mechanical" />
                <el-option label="办公用品" value="office" />
                <el-option label="清洁用品" value="cleaning" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="materialForm.unit" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="规格型号">
          <el-input v-model="materialForm.specification" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="当前库存" prop="current_stock">
              <el-input-number v-model="materialForm.current_stock" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最低库存" prop="min_stock">
              <el-input-number v-model="materialForm.min_stock" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最高库存">
              <el-input-number v-model="materialForm.max_stock" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单价">
              <el-input-number v-model="materialForm.unit_price" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商">
              <el-input v-model="materialForm.supplier" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="存放位置">
          <el-input v-model="materialForm.location" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="materialForm.notes" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showMaterialDialog = false">取消</el-button>
          <el-button type="primary" @click="saveMaterial" :loading="saving">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 库存调整对话框 -->
    <el-dialog
      v-model="showStockDialog"
      title="库存调整"
      width="400px"
    >
      <el-form
        ref="stockFormRef"
        :model="stockForm"
        :rules="stockRules"
        label-width="100px"
      >
        <el-form-item label="材料名称">
          <el-input :value="currentMaterial?.name" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input :value="currentMaterial?.stock_quantity" disabled />
        </el-form-item>
        <el-form-item label="调整类型" prop="type">
          <el-radio-group v-model="stockForm.type">
            <el-radio label="in">入库</el-radio>
            <el-radio label="out">出库</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number
            v-model="stockForm.quantity"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="调整原因" prop="reason">
          <el-input v-model="stockForm.reason" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showStockDialog = false">取消</el-button>
          <el-button type="primary" @click="saveStockAdjustment" :loading="saving">
            确认调整
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type UploadFile, type UploadInstance } from 'element-plus'
import {
  Upload,
  Plus,
  Search,
  Refresh,
  Download,
  Document,
  UploadFilled
} from '@element-plus/icons-vue'
import api from '@/api'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const materials = ref<any[]>([])
const filterForm = reactive({
  name: '',
  code: '',
  category: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 导入功能相关
const showImportDialog = ref(false)
const activeTab = ref('config')
const importLoading = ref(false)
const uploadRef = ref<UploadInstance>()
const uploadFile = ref<File | null>(null)
const previewData = ref<any[]>([])
const validationErrors = ref<string[]>([])

// 字段配置
const selectedFields = ref<string[]>(['code', 'name', 'category', 'unit', 'current_stock'])

// 导入字段定义
const importFields = ref([
  { key: 'code', label: '材料编码', required: true, type: 'text' },
  { key: 'name', label: '材料名称', required: true, type: 'text' },
  { key: 'category', label: '分类', required: true, type: 'select' },
  { key: 'specification', label: '规格型号', required: false, type: 'text' },
  { key: 'unit', label: '单位', required: true, type: 'text' },
  { key: 'current_stock', label: '当前库存', required: true, type: 'number' },
  { key: 'min_stock', label: '最低库存', required: false, type: 'number' },
  { key: 'max_stock', label: '最高库存', required: false, type: 'number' },
  { key: 'unit_price', label: '单价', required: false, type: 'number' },
  { key: 'supplier', label: '供应商', required: false, type: 'text' },
  { key: 'location', label: '存放位置', required: false, type: 'text' },
  { key: 'notes', label: '备注', required: false, type: 'textarea' }
])

// 材料管理相关
const showMaterialDialog = ref(false)
const isEdit = ref(false)
const materialFormRef = ref<FormInstance>()
const materialForm = reactive({
  code: '',
  name: '',
  category: '',
  specification: '',
  unit: '',
  current_stock: 0,
  min_stock: 0,
  max_stock: 0,
  unit_price: 0,
  supplier: '',
  location: '',
  notes: ''
})

const materialRules = {
  code: [{ required: true, message: '请输入材料编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入材料名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  current_stock: [{ required: true, message: '请输入当前库存', trigger: 'blur' }],
  min_stock: [{ required: true, message: '请输入最低库存', trigger: 'blur' }]
}

// 库存调整相关
const showStockDialog = ref(false)
const currentMaterial = ref<any>(null)
const stockFormRef = ref<FormInstance>()
const stockForm = reactive({
  type: 'in',
  quantity: 1,
  reason: ''
})

const stockRules = {
  type: [{ required: true, message: '请选择调整类型', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入调整原因', trigger: 'blur' }]
}

// 计算属性
const templateColumns = computed(() => {
  return importFields.value
    .filter(field => selectedFields.value.includes(field.key))
    .map(field => ({
      key: field.key,
      label: field.label,
      width: field.key === 'notes' ? 200 : 120
    }))
})

const templatePreview = computed(() => {
  const preview: any = {}
  templateColumns.value.forEach(column => {
    preview[column.key] = '示例数据'
  })
  return [preview]
})

const previewColumns = computed(() => {
  if (previewData.value.length === 0) return []
  
  const firstRow = previewData.value[0]
  return Object.keys(firstRow).map(key => ({
    key,
    label: getFieldLabel(key)
  }))
})

// 方法
const loadMaterials = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...filterForm
    }
    
    const response = await api.getMaterials(params)
    materials.value = response.data.materials || []
    pagination.total = response.data.total || materials.value.length
    pagination.page = response.data.current_page || pagination.page
  } catch (error) {
    console.error('加载材料列表失败:', error)
    ElMessage.error('加载材料列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilter = () => {
  Object.assign(filterForm, {
    name: '',
    code: '',
    category: '',
    status: ''
  })
  loadMaterials()
}

const getCategoryType = (category: string) => {
  const typeMap: Record<string, string> = {
    electronic: 'primary',
    mechanical: 'success',
    office: 'info',
    cleaning: 'warning',
    other: 'info'
  }
  return typeMap[category] || 'info'
}

const getCategoryLabel = (category: string) => {
  const labelMap: Record<string, string> = {
    electronic: '电子元件',
    mechanical: '机械配件',
    office: '办公用品',
    cleaning: '清洁用品',
    other: '其他'
  }
  return labelMap[category] || category
}

const getStockClass = (row: any) => {
  if (row.stock_quantity <= 0) return 'stock-out'
  if (row.stock_quantity <= row.min_stock) return 'stock-low'
  return 'stock-normal'
}

const getStatusType = (row: any) => {
  if (row.stock_quantity <= 0) return 'danger'
  if (row.stock_quantity <= row.min_stock) return 'warning'
  return 'success'
}

const getStatusLabel = (row: any) => {
  if (row.stock_quantity <= 0) return '缺货'
  if (row.stock_quantity <= row.min_stock) return '不足'
  return '充足'
}

// 导入功能方法
const getFieldLabel = (key: string) => {
  const field = importFields.value.find(f => f.key === key)
  return field ? field.label : key
}

const getFieldTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    text: 'info',
    number: 'success',
    select: 'warning',
    textarea: 'primary'
  }
  return colorMap[type] || 'info'
}

const getFieldTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    text: '文本',
    number: '数字',
    select: '选择',
    textarea: '多行文本'
  }
  return labelMap[type] || type
}

const openImportDialog = () => {
  showImportDialog.value = true
  activeTab.value = 'config'
}

const closeImportDialog = () => {
  showImportDialog.value = false
  uploadFile.value = null
  previewData.value = []
  validationErrors.value = []
  activeTab.value = 'config'
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const downloadTemplate = () => {
  const headers = templateColumns.value.map(col => col.label)
  const csvContent = headers.join(',') + '\n'
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', '材料导入模板.csv')
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const downloadSampleData = () => {
  const headers = templateColumns.value.map(col => col.label)
  const sampleRow = templateColumns.value.map(col => {
    switch (col.key) {
      case 'code': return 'M001'
      case 'name': return '示例材料'
      case 'category': return 'electronic'
      case 'specification': return '规格型号'
      case 'unit': return '个'
      case 'current_stock': return '100'
      case 'min_stock': return '10'
      case 'max_stock': return '1000'
      case 'unit_price': return '1.50'
      case 'supplier': return '示例供应商'
      case 'location': return 'A区-01'
      case 'notes': return '备注信息'
      default: return '示例值'
    }
  })
  
  const csvContent = headers.join(',') + '\n' + sampleRow.join(',') + '\n'
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', '材料导入示例.csv')
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const handleFileChange = (file: UploadFile) => {
  if (!file.raw) return false
  
  uploadFile.value = file.raw
  parseCSVFile(file.raw)
  return false
}

const beforeUpload = (file: File) => {
  const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv')
  if (!isCSV) {
    ElMessage.error('只能上传CSV文件')
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    return false
  }
  
  return true
}

const parseCSVFile = (file: File) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    const text = e.target?.result as string
    const lines = text.split('\n').filter(line => line.trim())
    
    if (lines.length < 2) {
      ElMessage.error('CSV文件格式错误，至少需要包含表头和一行数据')
      return
    }
    
    const headers = lines[0].split(',')
    const data = []
    
    for (let i = 1; i < lines.length; i++) {
      const values = lines[i].split(',')
      const row: any = {}
      
      headers.forEach((header, index) => {
        row[header.trim()] = values[index]?.trim() || ''
      })
      
      data.push(row)
    }
    
    previewData.value = data
    validateImportData(data)
  }
  
  reader.readAsText(file, 'utf-8')
}

const validateImportData = (data: any[]) => {
  const errors: string[] = []
  
  data.forEach((row, index) => {
    const rowNum = index + 2
    
    // 验证必填字段
    importFields.value.forEach(field => {
      if (field.required && selectedFields.value.includes(field.key)) {
        const fieldLabel = getFieldLabel(field.key)
        if (!row[fieldLabel] || row[fieldLabel].trim() === '') {
          errors.push(`第${rowNum}行：${fieldLabel} 不能为空`)
        }
      }
    })
    
    // 验证分类字段
    if (row['分类'] && !['electronic', 'mechanical', 'office', 'cleaning', 'other'].includes(row['分类'])) {
      errors.push(`第${rowNum}行：分类值无效，应为 electronic、mechanical、office、cleaning 或 other`)
    }
    
    // 验证数字字段
    const numberFields = ['当前库存', '最低库存', '最高库存', '单价']
    numberFields.forEach(field => {
      if (row[field] && isNaN(Number(row[field]))) {
        errors.push(`第${rowNum}行：${field} 必须是数字`)
      }
    })
  })
  
  validationErrors.value = errors
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleImport = async () => {
  if (validationErrors.value.length > 0) {
    ElMessage.error('请先修复数据验证错误')
    return
  }
  
  if (previewData.value.length === 0) {
    ElMessage.error('没有可导入的数据')
    return
  }
  
  importLoading.value = true
  
  try {
    let successCount = 0
    let failCount = 0
    
    for (const row of previewData.value) {
      try {
        const materialData: any = {}
        
        // 映射字段
        importFields.value.forEach(field => {
          if (selectedFields.value.includes(field.key)) {
            const fieldLabel = getFieldLabel(field.key)
            const value = row[fieldLabel]
            
            if (value !== undefined && value !== '') {
              if (field.type === 'number') {
                materialData[field.key] = Number(value)
              } else {
                materialData[field.key] = value
              }
            }
          }
        })
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 100))
        console.log('创建材料:', materialData)
        successCount++
      } catch (error) {
        console.error('创建材料失败:', error)
        failCount++
      }
    }
    
    ElMessage.success(`导入完成！成功创建 ${successCount} 个材料${failCount > 0 ? `，失败 ${failCount} 个` : ''}`)
    closeImportDialog()
    loadMaterials()
    
  } catch (error) {
    console.error('批量导入失败:', error)
    ElMessage.error('批量导入失败，请重试')
  } finally {
    importLoading.value = false
  }
}

// 材料管理方法
const openAddDialog = () => {
  isEdit.value = false
  Object.assign(materialForm, {
    code: '',
    name: '',
    category: '',
    specification: '',
    unit: '',
    current_stock: 0,
    min_stock: 0,
    max_stock: 0,
    unit_price: 0,
    supplier: '',
    location: '',
    notes: ''
  })
  showMaterialDialog.value = true
}

const editMaterial = (material: any) => {
  isEdit.value = true
  Object.assign(materialForm, material)
  showMaterialDialog.value = true
}

const saveMaterial = async () => {
  if (!materialFormRef.value) return
  
  try {
    await materialFormRef.value.validate()
    saving.value = true
    
    if (isEdit.value) {
      await api.updateMaterial(materialForm.id, materialForm)
    } else {
      await api.createMaterial(materialForm)
    }
    
    ElMessage.success(isEdit.value ? '材料更新成功' : '材料创建成功')
    showMaterialDialog.value = false
    loadMaterials()
  } catch (error) {
    console.error('保存材料失败:', error)
    ElMessage.error('保存材料失败，请重试')
  } finally {
    saving.value = false
  }
}

const deleteMaterial = async (material: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除材料 "${material.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.deleteMaterial(material.id)
    
    ElMessage.success('材料删除成功')
    loadMaterials()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除材料失败:', error)
      ElMessage.error('删除材料失败，请重试')
    }
  }
}

// 库存调整方法
const adjustStock = (material: any) => {
  currentMaterial.value = material
  Object.assign(stockForm, {
    type: 'in',
    quantity: 1,
    reason: ''
  })
  showStockDialog.value = true
}

const saveStockAdjustment = async () => {
  if (!stockFormRef.value) return
  
  try {
    await stockFormRef.value.validate()
    saving.value = true
    
    const adjustmentData = {
      operation: stockForm.type, // 'in' 或 'out'
      quantity: stockForm.quantity,
      reason: stockForm.reason
    }
    
    await api.updateStock(currentMaterial.value.id, adjustmentData)
    
    ElMessage.success('库存调整成功')
    showStockDialog.value = false
    loadMaterials()
  } catch (error) {
    console.error('库存调整失败:', error)
    ElMessage.error('库存调整失败，请重试')
  } finally {
    saving.value = false
  }
}

// 生命周期
onMounted(() => {
  loadMaterials()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.stock-normal {
  color: #67c23a;
  font-weight: bold;
}

.stock-low {
  color: #e6a23c;
  font-weight: bold;
}

.stock-out {
  color: #f56c6c;
  font-weight: bold;
}

.import-config {
  padding: 20px 0;
}

.field-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.field-grid .el-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
}

.template-section {
  padding: 20px 0;
}

.template-actions {
  margin: 20px 0;
  display: flex;
  gap: 10px;
}

.template-preview {
  margin-top: 20px;
}

.upload-section {
  padding: 20px 0;
}

.file-info {
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-section {
  margin-top: 20px;
}

.preview-info {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

.error-section {
  margin-top: 20px;
}

.error-more {
  margin-top: 10px;
  color: #f56c6c;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}
</style>